<template>
  <el-main>
    <el-row>

      <el-col :span="12" v-loading="api_loading" element-loading-text="AI自动化平台正在飞快解析中">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="方法名称" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="接口地址" prop="url">
            <el-input v-model="ruleForm.url"></el-input>
          </el-form-item>
          <el-form-item label="接口类型" prop="type">
            <el-select v-model="ruleForm.type" placeholder="请选择接口类型">
              <el-option label="get" value="get"></el-option>
              <el-option label="post" value="post"></el-option>
              <el-option label="deleted" value="deleted"></el-option>
              <el-option label="put" value="put"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="请求参数">
            <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入请求参数"
                v-model="ruleForm.params">
            </el-input>
          </el-form-item>
          <el-form-item label="静态检查点">
            <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入请求参数"
                v-model="ruleForm.check">
            </el-input>
          </el-form-item>
          <el-form-item label="多参数覆盖">
            <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入请求参数"
                v-model="ruleForm.multi_params">
            </el-input>
          </el-form-item>
          <el-form-item label="动态检查点">
            <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入请求参数"
                v-model="ruleForm.dy_check">
            </el-input>
          </el-form-item>
          <el-form-item label="平台支持" prop="lang_type">
            <el-select v-model="ruleForm.lang_type" placeholder="请选择语言">
              <el-option label="python" value="python"></el-option>
              <el-option label="java" value="java"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">代码生成</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="1"></el-col>
      <el-col :span="11">
        <el-button size="large" type="warning" round :disabled=down_disable @click="downloadResult(getFileType(),'result_api')">代码下载</el-button>
        <p id="result_api" style="color:red;white-space: pre-wrap">{{ result }}</p>
      </el-col>

    </el-row>
  </el-main>
</template>

<script>
//vue2 vue3
//import axios from 'axios'
// const axios = require('axios').default;
import {fetchEventSource} from '@microsoft/fetch-event-source';
export default {
  name: "api_test",
  data() {
    return {
      result: '',
      api_loading: false,
      down_disable: true,
      ruleForm: {
        name: '',
        check: '',
        dy_check: '',
        url: '',
        type: '',
        params: '',
        multi_params: '',
        lang_type: 'python'
      },
      rules: {
        name: [
          {required: true, message: '请输入接口名称', trigger: 'blur'}
        ],
        url: [
          {required: true, message: '请选择接口地址', trigger: 'blur'}
        ],
        type: [
          {required: true, message: '请至少选择一个接口协议', trigger: 'change'}
        ]
      }
    };
  },
  methods: {
    getFromValue(key) {
      if (this.ruleForm[key] === '') {
        return "没有,不需要"
      }
      if (key === 'dy_check') {
        return '动态检查点是参数化中 ' + this.ruleForm[key]
      }
      return this.ruleForm[key]
    },
    submitForm(formName) {
       document.getElementById("result_api").innerHTML=''
      this.$refs[formName].validate((valid) => {
            if (valid) {
              //处理下ruleForm //content
              this.api_loading = true
              var api_template = '1.角色:it工程师'
                  + '\n 2.任务:接口测试'
                  + '\n 3.接口测试方法名字 ' + this.ruleForm['name'] + ',发送请求异常处理'
                  + '\n 4.接口地址:' + this.ruleForm['url']
                  + '\n 5.接口类型:' + this.ruleForm['type']
                  + '\n 6.请求参数:' + this.getFromValue('params')
                  + '\n 7.参数化:' + this.getFromValue('multi_params')
                  + '\n 8.静态检查点:' + this.getFromValue('check')
                  + '\n 9.动态检查点:' + this.getFromValue('dy_check');

              if (this.ruleForm['lang_type'] === 'python') {
                api_template +=
                    +'\n 10.使用pytest-rerunfailures，支持失败重试，最多三次，每次失败延迟2秒，在接口测试方式上面实现'
                    + '\n 11.使用requests和pytest框架生成代码，包含main方法，支持pytest详细信息打印'
                    + '\n 12.生成python代码案例'
              } else {
                api_template +=
                    +'\n 10.使用java HttpClient和testNg框架，支持失败重试，最多三次，每次失败延迟2秒，在接口测试方式上面实现'
                    + '\n 11.生成java代码案例'
              }
              let chatobj = {}
              chatobj.content = api_template
              let self = this
              //异步框架  http
              // axios.post('http://127.0.0.1:5000/chat', JSON.stringify(chatobj), {
              //   headers: {
              //     'Content-Type': 'application/json'
              //   }
              // }).then(function (response) {
              //   self.result = response.data
              //   self.api_loading = false
              //   self.down_disable = false
              // }).catch(function (error) {
              //   console.log(error)
              //   self.result = '请重试'
              //   self.api_loading = false
              // });
              let controller = new AbortController()
              const eventSource = fetchEventSource('http://127.0.0.1:5000/chat2', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(
                    chatobj
                ),
                signal: controller.signal,
                onopen() {
                  console.log('open')
                },
                onmessage(event) {
                  console.log('onMessage', event.data)
                  if (event.data === '[DONE]') {
                    self.api_loading = false
                    self.down_disable = false
                    controller.abort();
                    eventSource.close();
                  }else{
                    document.getElementById("result_api").innerHTML =
                      document.getElementById("result_api").innerHTML + event.data
                  }
                },
                onclose() {
                  controller.abort();
                  eventSource.close();
                },
                onerror(error) {
                  console.log('close', error)
                  controller.abort();
                  eventSource.close();
                  document.getElementById("result_api").innerHTML ='AI繁忙,请重试'
                }
              })
            } else {
              this.$message.error('数据缺失');
              return false;
            }
          }
      );
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getFileType(){
      if(this.ruleForm['lang_type']==='python'){
        return 'py'
      }else{
        return 'java'
      }
    },
    downloadResult(fileType, resultId) {
      let text = document.getElementById(resultId).innerText;
      let element = document.createElement("a");
      let file = new Blob([text], {type: 'text/plain'});
      element.href = URL.createObjectURL(file);
      element.download = "download." + fileType;
      element.click();
    },


  }
}
</script>

<style scoped>

</style>